package lab01;

public class 计算二进制中1的个数 {

    // 整数n每次右移1位，然后判断个位是否为1
    static int count1(int n) {

        int count = 0;

        while (n != 0) {

            if ((n & 1) == 1)
                count++;

            n >>>= 1;
        }

        return count;
    }

    // 从右向左依次判断每一位是否为1
    static int count2(int n) {

        int count = 0;

        int shift = 1;

        for (int i = 0; i < 32; i++) {

            if ((n & shift) == shift)
                count++;

            shift <<= 1;
        }

        return count;
    }

    // 从后向前依次消除一个1
    static int count3(int n) {

        int count = 0;

        while (n != 0) {

            n = (n - 1) & n;
            count++;

        }
        return count;
    }

    static int count4(int n) {

        if (n == 0)
            return 0;

        return ((n&1) == 1 ? 1:0) + count4(n/2);
    }

    public static void main(String[] args) {

        int n = 1351;
        System.out.println(Integer.toBinaryString(n));
        System.out.println(count4(n));
    }
}
